package com.last1mile.web.control;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.multipart.MultipartFile;

import com.last1mile.commons.DirectoryConst;
import com.last1mile.model.Login;
import com.last1mile.model.ServeView;
import com.last1mile.pojo.MerServeDO;
import com.last1mile.pojo.TradeDO;
import com.last1mile.pojo.UserDO;
import com.last1mile.service.ReserveService;
import com.last1mile.service.ServeService;
import com.last1mile.service.TradeService;
import com.last1mile.service.UserService;

@Controller
@RequestMapping("/*")
@SessionAttributes("currentLogin")
public class UserController {

    @Autowired
    @Qualifier("userServiceImpl")
    UserService  userService;

    @Autowired
    @Qualifier("serveServiceImpl")
    ServeService serveService;
    
    @Autowired
    @Qualifier("tradeServiceImpl")
    TradeService tradeService;
    
    @Autowired
    @Qualifier("reserveServiceImpl")
    ReserveService reserveService;

    /**
     * 个人公众页面
     * @param loginId
     * @param model
     * @return
     */
    @RequestMapping(value = "/{loginId}", method = RequestMethod.GET)
    public String publicUser(@PathVariable String loginId, ModelMap model) {
        UserDO userDo = this.userService.queryUserByLoginId(loginId);
        if (userDo != null) {
            List<MerServeDO> merServeList = this.serveService.queryServesByMerId(userDo.getId());
            model.addAttribute("merServeList", merServeList);
            model.addAttribute("user", userDo);
            return "user/PublicUser";
        } else {
            return "user/UserNotExist";
        }
    }

    /**
     * 个人私人页面
     * @param loginId
     * @param login
     * @param model
     * @return
     */
    @RequestMapping(value = "/u/{loginId}/profile.html", method = RequestMethod.GET)
    public String privateUser(@PathVariable String loginId, @ModelAttribute("currentLogin") Login login, ModelMap model) {
        //用户信息
        UserDO userDo = this.userService.queryUserByLoginId(loginId);
        model.addAttribute("user", userDo);
        return "user/PrivateUser";
    }
    
    @RequestMapping(value = "/u/{userId}/serve.html", method = RequestMethod.GET)
    public String privateUserServe(@PathVariable Integer userId, @ModelAttribute("currentLogin") Login login, ModelMap model){
        //作为卖家发布的服务
        List<ServeView> merServeViewList = this.buildMerServeViewList(userId);
        model.addAttribute("merServeViewList", merServeViewList);
        
        //作为买家关注的服务
        List<ServeView> perServeViewList = this.buildPerServeViewList(userId);
        model.addAttribute("perServeViewList", perServeViewList);
        
        return "user/PrivateUserServe";
    }
    
    @RequestMapping(value = "/u/{userId}/trade.html", method = RequestMethod.GET)
    public String privateUserTrade(@PathVariable String userId, @ModelAttribute("currentLogin") Login login, ModelMap model){
        //作为卖家卖出的交易
        List<TradeDO> merTradeList = this.tradeService.queryTradeByMer(login.getUserId());
        model.addAttribute("merTradeList", merTradeList);
        
        //作为买家购买的交易
        List<TradeDO> perTradeList = this.tradeService.queryTradeByPer(login.getUserId());
        model.addAttribute("perTradeList", perTradeList);
        return "user/PrivateUserTrade";
    }
    
    @RequestMapping(value = "/u/{userId}/reserve.html", method = RequestMethod.GET)
    public String privateUserReserve(@PathVariable String userId, @ModelAttribute("currentLogin") Login login, ModelMap model){
        
        return "user/PrivateUserReserve";
    }
    
    
    /**
     * 作为卖家发布的服务
     * @param userId
     * @return
     */
    private List<ServeView> buildMerServeViewList(Integer userId){
        List<ServeView> merServeViewList = new ArrayList<ServeView>();
        
        List<MerServeDO> merServeList = this.serveService.queryServesByMerId(userId);
        for(MerServeDO merServeDo : merServeList){
            ServeView sv = new ServeView();
            sv.setServeDo(merServeDo);
            // 该服务的预约总数
            Integer reserveCount = this.reserveService.countServeReserve(merServeDo.getId());
            sv.setReserveCount(reserveCount);
            merServeViewList.add(sv);
        }
        
        return merServeViewList;
    }
    
    /**
     * 作为买家关注的服务
     * @param userId
     * @return
     */
    private List<ServeView> buildPerServeViewList(Integer userId){
        List<ServeView> perServeViewList = new ArrayList<ServeView>();
        
        List<MerServeDO> perServeList = this.serveService.queryServesByPerId(userId);
        for(MerServeDO merServeDo : perServeList){
            ServeView sv = new ServeView();
            sv.setServeDo(merServeDo);
            // 该服务的预约总数
            Integer reserveCount = this.reserveService.countServeReserve(merServeDo.getId());
            sv.setReserveCount(reserveCount);
            perServeViewList.add(sv);
        }
        return perServeViewList;
    }
    
    
    
    /**
     * 用户上传头像图片，更名存储到指定目录
     * @param file
     * @param loginId
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/u/{loginId}/uploadImage", method = RequestMethod.POST)
    public String processImageUpload(@RequestParam("file") MultipartFile file,@PathVariable String loginId,@ModelAttribute("currentLogin") Login login, ModelMap model)throws Exception {
        if(!file.isEmpty()){
            //存用户头像文件
            byte[] bytes = file.getBytes();
            String originalFileName = file.getOriginalFilename();
            int i = originalFileName.lastIndexOf('.');
            String ext = "";
            if (i > 0 &&  i < originalFileName.length() - 1) {
                ext = originalFileName.substring(i+1).toLowerCase();
            }
            String userPicDir = loginId+"."+ext;
            
            File userImage = new File(DirectoryConst.USER_IMAGE_ROOT_DIR,userPicDir);
            FileOutputStream fos = new FileOutputStream(userImage.getAbsolutePath());
            fos.write(bytes);
            //更新用户头像文件路径
            this.userService.updateUserPic(login.getUserId(), userPicDir);
            
            //用户信息
            UserDO userDo = this.userService.queryUserByLoginId(loginId);
            model.addAttribute("user", userDo);
            
            //作为卖家发布的服务
            List<ServeView> merServeViewList = this.buildMerServeViewList(login.getUserId());
            model.addAttribute("merServeViewList", merServeViewList);
            
            //作为卖家卖出的交易
            List<TradeDO> merTradeList = this.tradeService.queryTradeByMer(login.getUserId());
            model.addAttribute("merTradeList", merTradeList);
            
            //作为买家关注的服务
            List<ServeView> perServeViewList = this.buildPerServeViewList(login.getUserId());
            model.addAttribute("perServeViewList", perServeViewList);
            
            //作为买家购买的交易
            List<TradeDO> perTradeList = this.tradeService.queryTradeByPer(login.getUserId());
            model.addAttribute("perTradeList", perTradeList);
        }
        return "user/PrivateUser";
    }
    
    /**
     * 显示用户头像
     * @param userPicFileName
     * @param userPicFileExt
     * @param request
     * @param response
     */
    @RequestMapping(value = "/u/image/{userPicFileName}.{userPicFileExt}", method = RequestMethod.GET)
    public void getUserPic(@PathVariable String userPicFileName,@PathVariable String userPicFileExt,HttpServletRequest request,HttpServletResponse response){
    	File userImage = new File(DirectoryConst.USER_IMAGE_ROOT_DIR,userPicFileName+"."+userPicFileExt);
    	if(userImage != null){
    		try {
				FileInputStream fis = new FileInputStream(userImage);
				if(fis != null){
					int len = fis.available();
					byte[] fileByte = new byte[len];
					fis.read(fileByte);
					
					OutputStream out = response.getOutputStream();
					out.write(fileByte);  //打印图片
					out.flush();
					
					fis.close();
					out.close();
				}
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			} 
    	}
    }
}
